<?php
namespace app\controller;

use support\Db;
use support\Request;

class SnController
{
    public function login(Request $request)
    {
        $from      = $request->input('from');
        $code      = $request->input('code');
        $env       = $request->input('env');
        $appid     = config('key.SN_APPID');
        $appsecret = config('key.SN_APPSECRET');

        if ($env == 'development') {
            $res['openid'] = 'abc123456789';
        } else {
            $res = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code");
            $res = json_decode($res, true);
        }

        $user = Db::table('wa_sn_user')->where('openid', $res['openid'])->first();
        if (!$user) {
            $user = [
                'openid'      => $res['openid'],
                'coin'        => 1,
                'create_time' => time(),
            ];
            Db::table('wa_sn_user')->insert($user);

            if ($from) {
                Db::table('wa_sn_invite_log')->insert(['openid' => $from, 'to' => $res['openid'], 'time' => time()]);

                $count = Db::table('wa_sn_invite_log')->where('openid', $from)->count();
                if ($count) {
                    $reward = getReward($count+1);
                    if ($reward) {
                        Db::table('wa_sn_user')->where('openid', $from)->increment('coin', $reward);
                    }
                }

            }
        }

        $share = [
            'title'    => '查询苹果手机激活和保修',
            'desc'     => '🔥🔥🔥朋友圈都在问怎么弄的',
            'path'     => '/pages/index/index?from=' . $res['openid'],
            'imageUrl' => 'https://web.h5sdk.com/common/fg/share.jpg',
        ];

        return json(['code' => 0, 'msg' => '登录成功', 'data' => $user, 'share' => $share]);
    }

    public function result(Request $request)
    {
        $openid = $request->header('X-token');
        $sn  = $request->input('sn');

        $user = (array) Db::table('wa_sn_user')->where('openid', $openid)->first();

        if (!$user) {
            return json(['code' => -1, 'msg' => '识别用户失败']);
        }

        if ($user['coin'] == 0) {
            return json(['code' => 999, 'msg' => '次数不足，观看视频可增加次数哦~', 'data' => $user]);
        }

        //JYK271WW5T 
        $data = file_get_contents("https://data.06api.com/api.php?key=269cc1c7eec0696df15892884920a524&type=apple_warranty&sn={$sn}");
        // $data = '{
        //     "code": 0,
        //     "data": {
        //         "serial": "JYK271WW5T",
        //         "model": "iPhone 17 Pro Max",
        //         "thumbnail": "https:\/\/support.apple.com\/content\/dam\/edam\/applecare\/images\/en_US\/applecare\/ios\/PGF31017_3x.png",
        //         "replaced": false,
        //         "registered": false,
        //         "activated": false,
        //         "validPurchaseDate": false,
        //         "acEligible": true,
        //         "loaner": false,
        //         "pre-activated": "unknown",
        //         "warrantyYear": 1,
        //         "warrantyStatus": "\u5728\u4fdd",
        //         "appleCare": false,
        //         "appleCareVerifyed": true
        //     }
        // }';
        $data = json_decode($data, true);

        $keyMap = [
            'serial' => '序列号',
            'model' => '型号',
            //'thumbnail' => '产品图片',
            //'replaced' => '是否已更换产品的序列号',
            //'registered' => '是否已注册设备',
            'activated' => '是否已激活',
            //'loaner' => '是否借出设备',
            //'validPurchaseDate' => '是否已验证设备',
            'warrantyDaysRemaining' => '保修剩余天数',
            //'acEligible' => '在线购买AppleCare的资格',
            'estPurchaseDate' => '预激活/购买日期',
            'activeDate' => '激活日期',
            'warrantyStatus' => '保修状态',
            'repairExpiry' => '保修到期日期',
            'warrantyYear' => '保修年数',
            //'appleCare' => '是否已购买AppleCare',
            //'acExpiry' => 'AC结束日期',
            //'acDaysRemaining' => 'AC剩余天数'
        ];

        if($data) {
            $map = [];
            foreach($data['data'] as $k => $v) {
                if(isset($keyMap[$k])) {

                    if($k == 'activated') {
                        $v = $v ? '已激活' : '未激活';
                    }
                    $map[$keyMap[$k]] = $v;
                }
            }
            $data['data'] = $map;
            Db::table('wa_sn_user')->where('openid', $openid)->decrement('coin', 1);

            return json(['code' => 0, 'msg' => 'succ', 'data' => $map, 'coin' => (int) $user['coin'] - 1]);
        }

        return json($data);
    }

    public function watchAd(Request $request)
    {   
        $openid = $request->header('X-token');
        if (!$openid) {
            return json(['code' => -1, 'msg' => 'error']);
        }

 
        Db::table('wa_sn_user')->where('openid', $openid)->increment('coin', 1);
        
        $user = (array) Db::table('wa_sn_user')->where('openid', $openid)->first();

        return json(['code' => 0, 'msg' => 'succ', 'data' => $user['coin']]);
    }
   
}



/**
'serial': 'CJ2WHY2246',   //序列号
'model': 'iPhone 15',   //型号
'thumbnail': 'https://cdsassets.apple.com/content/services/pub/image?productid=300991&size=240x240',   //产品图片
'replaced': false,   //是否已更换产品的序列号
'registered': true,   //是否已注册设备
'activated': true,   //是否已激活
'loaner': false,   //是否借出设备 (true false unknown)
'validPurchaseDate': true,   //是否已验证设备
'warrantyDaysRemaining': 319,   //保修剩余天数
'acEligible': true,   //在线购买AppleCare的资格
'estPurchaseDate': '2024-08-14',   //预激活/购买日期
'activeDate': '2024-08-14',   //激活日期，不返回activeDate的时候取estPurchaseDate
'warrantyStatus': '在保',   //保修状态
'repairExpiry': '2025-08-13',   //保修到期日期
'warrantyYear': 1,   //保修年数
'appleCare': false,   //是否已购买AppleCare
'acExpiry': '',   //AC结束日期  有AC的机器才返回
'acDaysRemaining': '',   //AC剩余天数  有AC的机器才返回


{
    "code": 0,
    "data": {
        "serial": "JYK271WW5T",
        "model": "iPhone 17 Pro Max",
        "thumbnail": "https:\/\/support.apple.com\/content\/dam\/edam\/applecare\/images\/en_US\/applecare\/ios\/PGF31017_3x.png",
        "replaced": false,
        "registered": false,
        "activated": false,
        "validPurchaseDate": false,
        "acEligible": true,
        "loaner": false,
        "pre-activated": "unknown",
        "warrantyYear": 1,
        "warrantyStatus": "\u5728\u4fdd",
        "appleCare": false,
        "appleCareVerifyed": true
    }
}
 */